import { IHooksOptions } from '@/hooks/interface'
import service from '@/utils/request'
import { onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import qs from 'qs'
import cache from "@/utils/cache";
import { fullBaseAPI_URL } from "@/utils/tool";
import { ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import { useAppStore } from '@/store/modules/app'

export const useCrud = (options: IHooksOptions) => {
    const defaultOptions: IHooksOptions = {
        createdIsNeed: true,
        dataListUrl: '',
        isPage: true,
        deleteUrl: '',
        primaryKey: 'id',
        exportUrl: '',
        queryForm: {},
        moreQuery: false,
        dataList: [],
        order: '',
        asc: false,
        page: 1,
        limit: 10,
        total: 0,
        pageSizes: [10, 20, 50, 100, 200],
        dataListLoading: false,
        dataListSelections: []
    }

    const mergeDefaultOptions = (options: any, props: any): IHooksOptions => {
        for (const key in options) {
            if (!Object.getOwnPropertyDescriptor(props, key)) {
                props[key] = options[key]
            }
        }
        return props
    }

    // 覆盖默认值
    const state = mergeDefaultOptions(defaultOptions, options)

    onMounted(() => {
        if (state.createdIsNeed) {
            query()
        }
    })

    // 显示隐藏查询参数
    const handleMoreQuery = () => {
        state.moreQuery = !state.moreQuery
    }

    const query = (reloadDict?: boolean) => {
        if (!state.dataListUrl) {
            return
        }

        state.dataListLoading = true

        service.get(state.dataListUrl, {
            params: {
                order: state.order,
                asc: state.asc,
                page: state.isPage ? state.page : null,
                limit: state.isPage ? state.limit : null,
                ...state.queryForm
            },
            paramsSerializer: params => {
                return qs.stringify(params)
            }
        })
            .then((res: any) => {
                state.dataList = state.isPage ? res.data.list : res.data

                state.total = state.isPage ? res.data.total : 0
            })
            .finally(async () => {
                state.dataListLoading = false
                // 针对动态字典处理 重载全局字典数据
                if (reloadDict) {
                    const appStore = useAppStore()
                    await appStore.getDictListAction()
                }
            })
    }

    const getDataList = (reloadDict?: boolean) => {
        state.page = 1
        query(reloadDict)
    }

    //导出
    const exportDataList = () => {
        location.href = `${fullBaseAPI_URL() + state.exportUrl}?access_token=${cache.getToken()}&${qs.stringify(state.queryForm)}`

    }


    const sizeChangeHandle = (val: number) => {
        state.page = 1
        state.limit = val
        query()
    }

    const currentChangeHandle = (val: number) => {
        state.page = val
        query()

    }

    // 多选
    const selectionChangeHandle = (selections: any[]) => {
        state.dataListSelections = selections.map((item: any) => state.primaryKey && item[state.primaryKey])
    }

    // 排序
    const sortChangeHandle = (data: any) => {
        const { prop, order } = data

        if (prop && order) {
            state.order = prop
            state.asc = order === 'ascending'
        } else {
            state.order = ''
        }

        query()
    }

    const deleteHandle = (key: number | string) => {
        if (!state.deleteUrl) {
            return
        }

        ElMessageBox.confirm('确定进行删除操作?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
            .then(() => {
                service.delete(state.deleteUrl + '/' + key).then(() => {
                    ElMessage.success('删除成功')

                    query()
                })
            })
            .catch(() => {
            })
    }

    const deleteBatchHandle = (key?: number | string, reloadDict?: boolean) => {
        let data: any[] = []
        if (key) {
            data = [key]
        } else {
            data = state.dataListSelections ? state.dataListSelections : []

            if (data.length === 0) {
                ElMessage.warning('请选择删除记录')
                return
            }
        }

        ElMessageBox.confirm('确定进行删除操作?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
            .then(() => {
                if (state.deleteUrl) {
                    service.delete(state.deleteUrl, { data }).then(() => {
                        ElMessage.success('删除成功')

                        query(reloadDict)
                    })
                }
            })
            .catch(() => {
            })
    }

    const downloadHandle = async (url: string, filename?: string, method: string = 'GET'): Promise<any> => {
        try {
            const res = await service({
                responseType: 'blob',
                url: url,
                method: method
            })
            // 创建a标签
            const down = document.createElement('a')

            console.log("res", res)
            // 文件名没传，则使用时间戳
            if (filename) {
                down.download = filename
            } else {
                const downName = res.headers['content-disposition'].split('=')[1]
                down.download = decodeURI(downName)
            }

            // 隐藏a标签
            down.style.display = 'none'

            // 创建下载url
            down.href = URL.createObjectURL(
                new Blob([res.data], {
                    type: res.data.type
                })
            )

            // 模拟点击下载
            document.body.appendChild(down)
            down.click()

            // 释放URL
            URL.revokeObjectURL(down.href)
            // 下载完成移除
            document.body.removeChild(down)
        } catch (err: any) {
            ElMessage.error(err.message)
        }
    }

    return {
        getDataList,
        exportDataList,
        sizeChangeHandle,
        currentChangeHandle,
        selectionChangeHandle,
        sortChangeHandle,
        deleteHandle,
        deleteBatchHandle,
        downloadHandle,
        handleMoreQuery,
        ArrowDown,
        ArrowUp,
    }
}
